<template>
  <div>
    <el-dialog
      title="选择图片"
      :show-close="false"
      :before-close="closeModle"
      :visible.sync="dialogVisible"
      width="66%"
    >
      <div class="img-main">
        <div class="img-sidebar">
          <ul>
            <li v-for="(item, idx) in sidebar" :key="idx" @click="activeIdx(item.id)">
              <span :class="actIdx === idx ? 'active': ''">{{item.name}}</span>
            </li>
          </ul>
        </div>
        <div class="line"></div>
        <div class="img-con">
          <div class="img-show">
            <div
              v-for="(item,key) in fileList"
              @click="checkImg(key, item.url, item.name)"
              :key="key"
              :class="[checkImgIdx === key ? 'cheackImg': '', 'img-li-box']"
            >
              <div size="mini" :class="[item.status? '':'unload', 'upload-status']">
                <span>{{item.status? '成功':'待定'}}</span>
              </div>
              <img class="img-li-b--url" :src="item.url" />
              <!-- 操作 -->
              <div class="img-li-b--layer">
                <i class="el-icon-view" @click="showPreview(item.url)"></i>
                <i class="el-icon-edit" @click="cutFile(item.url)"></i>
                <i @click="handleRemove(item.name)" class="el-icon-delete"></i>
              </div>
            </div>
            <div class="img-li-b--upload">
              <el-upload
                action="#"
                list-type="picture-card"
                accept="image/*"
                multiple
                :show-file-list="false"
                :auto-upload="false"
                :on-change="beforeUp"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
            <el-dialog :visible.sync="showCut" title="裁剪图片" append-to-body>
              <CutImg @closeModel="closeCut" v-if="showCut" :actIdx="actIdx" :cutImg="cutImg"></CutImg>
            </el-dialog>
            <el-dialog :visible.sync="showDialog" append-to-body>
              <img width="100%" :src="dialogImageUrl" alt />
            </el-dialog>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <!--分页-->
        <el-pagination
          style="float:left;margin-left:150px"
          small
          layout="prev, pager, next"
          @current-change="changeData"
          :total="1000"
        ></el-pagination>
        <el-button type="primary" @click="goUpImgs">开始上传</el-button>
        <el-button @click="closeModle(0)">取 消</el-button>
        <el-button type="primary" @click="closeModle(1)">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { getImgList, getImgSort, delImgs } from "@/api/common";
import { BASE_URL } from "@/utils/request";
import CutImg from "./CutImg";
import axios from "axios";
export default {
  props: ["dialogVisible"],
  components: { CutImg },
  computed: {
    ...mapGetters(["token", "ImgUrl"])
  },
  data() {
    return {
      actIdx: 0,
      checked: false,
      fileList: [],
      showDialog: false,
      dialogImageUrl: "",
      cut_type: "",
      baseUrl: BASE_URL,
      formData: {},
      initPage: 0,
      sidebar: [],
      imgData: [],
      upIdx: 0,
      checkImgIdx: 0,
      off: false,
      showCut: false,
      exportImg: "",
      cutImg:
        "https://zltc-1255680458.cos.ap-beijing.myqcloud.com/1564035035.jpg"
    };
  },
  watch: {
    actIdx: function(val) {
      // 清空图片列表
      this.fileList = [];
      // 切换图片列表
      this.getUpImg(val);
    },
    upIdx: function(val) {
      this.goUpImgs();
      return val;
    },
    ImgUrl: function(val) {
      this.$emit("changeImg", val);
    }
  },
  mounted() {
    // 加载左侧类别
    this.getImgSort();
    // 加载图片列表
    this.getUpImg();
  },
  methods: {
    closeCut() {
      this.showCut = false;
    },
    activeIdx(idx) {
      this.actIdx = idx;
    },
    // 选中图片
    checkImg(idx, url, imgId) {
      console.log(idx, url, imgId)
      this.checkImgIdx = idx;
      this.exportImg = url;
      // 设置store图片内容
      this.$store.commit("imgs/SET_IMGId", imgId);
    },
    // 分页
    changeData(idx) {
      // 设置页码
      this.initPage = idx;
      this.getUpImg(this.actIdx);
    },
    // 加载图片类别
    getImgSort() {
      getImgSort().then(res => {
        if (res.data.length > 0) {
          this.sidebar = res.data;
        }
      });
    },
    // 裁剪
    cutFile(url) {
      this.cutImg = url;
      this.showCut = true;
    },
    // 预览
    showPreview(url) {
      this.dialogImageUrl = url;
      this.showDialog = true;
    },
    // 关闭模态框
    closeModle(val) {
      if (val === 1) {
        this.$store.commit("imgs/SET_IMGURL", this.exportImg);
      }
      // 导出图片地址
      this.$emit("closeModel", false);
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    // 加载图片
    getUpImg(type) {
      getImgList(this.initPage, type).then(res => {
        if (res.data.length > 0) {
          this.fileList = [];
          for (const i in res.data) {
            const obj = {};
            obj.name = res.data[i].id;
            obj.url = res.data[i].url;
            obj.status = 1;
            this.fileList.push(obj);
          }
        } else {
          // 禁止点击分页
          this.$message.warning("没有更多了...");
          this.off = true;
        }
      });
    },
    // 文件超出限制个数
    moreFile(file, fileList) {
      this.$message.warning("每次最多选择5个图片");
    },
    beforeUp(file, fileList) {
      const M = 1024 * 1024;
      const size = 1 * M;
      if (file.size > size) {
        this.$message.error("文件超出1M,请重新选择...");
        return;
      } else {
        console.log(file)
        const obj = {};
        obj.name = file.name;
        obj.url = file.url;
        obj.status = 0;
        this.fileList.push(obj);
        this.imgData.push(file.raw);
      }
    },
    // 多图上传图片
    goUpImgs() {
      if (this.upIdx >= this.imgData.length) {
        this.getUpImg();
        return;
      } else {
        this.subPicForm(this.imgData[this.upIdx]).then(res => {
          if (res) {
            this.upIdx++;
            this.$notify({
              title: "成功",
              message: `第${this.upIdx}个上传成功`,
              type: "success"
            });
          } else {
            return;
          }
        });
      }
    },
    // 异步上传单个图片
    subPicForm(file) {
      const that = this;
      return new Promise(function(resolve, reject) {
        that.formData = new FormData();
        that.formData.append("token", that.token);
        that.formData.append("image", file);
        that.formData.append("type", "1");
        that.formData.append("file_group", that.actIdx);
        const config = {
          headers: {
            "Content-Type": "multipart/form-data"
          }
        };
        axios
          .post(`${BASE_URL}/api/Upload/uploads`, that.formData, config)
          .then(res => {
            if (res.data.code === 200) {
              resolve(true);
            }
          })
          .catch(err => {
            this.$message.error("上传失败...");
            reject(err);
          });
      });
    },
    // 删除图片
    handleRemove(imgID) {
      delImgs(imgID).then(res => {
        if (res.code === 200) {
          this.$message.success("删除成功");
          for (const i in this.fileList) {
            if (this.fileList[i].name === imgID) {
              this.fileList.splice(i, 1);
            }
          }
        }
      });
    }
  }
};
</script>
<style scoped>
::-webkit-scrollbar {
  width: 6px;
  height: 16px;
  background-color: #f5f5f5;
}
.el-upload .el-upload--picture-card {
  width: 100%;
  height: auto;
}

/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  border-radius: 10px;
  background-color: #f5f5f5;
}
/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb {
  border-radius: 3px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.3);
  background-color: #dfdfdf;
}
</style>
<style lang="scss" scoped>
.line {
  width: 1px;
  height: 100%;
  background: #dfdfdf;
}
.img-main {
  width: 100%;
  height: 500px;
  display: flex;
  padding: 20px 0;
  margin-top: -20px;
  border-top: 1px solid #dfdfdf;
  overflow: hidden;
  .img-sidebar {
    width: 13%;
    padding-right: 30px;
    ul,
    li {
      height: auto;
      margin: 0;
      padding: 0;
      list-style: none;
      li {
        width: 100%;
        line-height: 30px;
        text-align: center;
        font-size: 16px;
        color: #353535;
        cursor: pointer;
        margin-top: 30px;
      }
      li > span.active {
        color: #008aff;
      }
    }
  }
  .img-con {
    flex: 1;
    height: 500px;
    padding: 20px;
    overflow-y: auto;
    .img-con-top {
      width: 100%;
      height: 40px;
      display: flex;
      justify-content: space-between;
    }
  }
  .img-show {
    width: 100%;
    height: auto;
    padding: 10px 0 0 24px;
    margin-left: -18px;
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    .img-li-box {
      position: relative;
      width: 148px;
      height: auto;
      box-sizing: border-box;
      padding: 5px;
      text-align: left;
      margin: 5px 16px 20px 0;
      border: 1px solid #d1dbe5;
      border-radius: 4px;
      transition: all 0.3s;
      box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.12), 0 0 6px 0 rgba(0, 0, 0, 0.04);
      .upload-status {
        position: absolute;
        top: 0;
        right: 0;
        width: 0;
        height: 0;
        color: #fff;
        border-top: 50px solid #008aff;
        border-left: 50px solid transparent;
        font-size: 12px;
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
        span {
          margin-top: -60px;
          margin-left: -25px;
          transform: rotate(45deg);
        }
      }
      .upload-status.unload {
        border-top: 50px solid #1c1e21;
        border-left: 50px solid transparent;
      }
      // 图片
      .img-li-b--url {
        display: block;
        width: 100%;
        height: 138px;
        margin: 0 auto;
        border-radius: 4px;
      }
      // 底部
      .img-li-b--bottom {
        margin-top: 10px;
        // 名称
        .img-li-b--name {
          width: 90%;
          text-overflow: ellipsis;
          overflow: hidden;
          height: 25px;
          line-height: 25px;
        }
      }
      // 删除按钮
      .img-li-b--delete {
        position: absolute;
        bottom: 10px;
        right: 10px;
        color: #8492a6;
        cursor: pointer;
        font-size: 1.1em;
      }
      // 放大遮罩层
      .img-li-b--layer {
        position: absolute;
        left: 0;
        right: 0;
        top: 0;
        height: 148px;
        color: #fff;
        text-align: center;
        z-index: 5;
        background-color: rgba(0, 0, 0, 0.4);
        // 放大按钮
        i {
          font-size: 1.6em;
          margin-top: 60px;
          margin-left: 10px;
          cursor: pointer;
        }
      }
      .img-li-b--delete,
      .img-li-b--layer {
        opacity: 0;
        transition: all 0.3s;
      }
      // 悬浮可见删除 or 放大按钮
      &:hover {
        .img-li-b--delete,
        .img-li-b--layer {
          opacity: 1;
        }
      }
      // 上传进度
      &.img-li-b--progress {
        text-align: center;
        padding-top: 50px;
      }
    }
    .cheackImg {
      border-radius: 2px;
      border: 3px solid rgba(0, 138, 255, 1);
    }
    // 上传按钮
    .img-li-b--upload {
      float: left;
      display: table;
      text-align: center;
      margin-top: 8px;
      .img-li-b--upl--field {
        width: 100%;
        display: table-cell;
        vertical-align: middle;
      }
    }
    ul,
    li {
      padding: 0;
      margin: 0;
      list-style: none;
    }
    li {
      width: 100px;
      height: 100px;
      border-radius: 3px;
      border: 1px solid #dfdfdf;
      overflow: hidden;
      margin: 20px 0 0 20px;
      .img-show-item {
        position: relative;
        width: 100%;
        height: 100%;
        .cheackImg {
          position: absolute;
          right: -28px;
          top: 0;
        }
        .cut-img {
          position: absolute;
          bottom: 0;
          left: 0;
          width: 100%;
          height: 20px;
          line-height: 20px;
          color: #fff;
          background: rgba(40, 117, 255, 0.3);
          text-align: center;
          cursor: pointer;
        }
        img {
          width: 100%;
          height: 100%;
        }
      }
    }
  }
}
</style>
